/*
Copyright (c) 2012 VBChunguk

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/

#ifndef __VBCDANMAKU__
#define __VBCDANMAKU__
#pragma once

#include <math.h>
#include <stdint.h>
#include <fstream>
#include <string>
#include <list>
#include <vector>
#include <stack>
#include <d3dx9.h>
#include "d3dUtility.h"
using namespace std;

namespace Danmaku
{
	class GlobalScript;
	class Danmaku;
	class DanmakuException;
	enum _DanmakuGraphic;

#pragma pack(push,1)
	typedef struct
	{
		uint32_t position;
		uint8_t namelen;

		string name;
	} EntryData;
#pragma pack(pop)

#pragma pack(push,1)
	typedef struct
	{
		char magic[4];
		uint32_t EntryPos;
		uint32_t DataPos;
		uint32_t CodePos;
	} ScriptHeader;
#pragma pack(pop)

#pragma pack(push,1)
	typedef struct
	{
		char name[4];
		uint32_t length;
		uint32_t position;
		uint32_t zero;

		char *description;
		char *data;
	} SectionHeader;
#pragma pack(pop)

#pragma pack(push,1)
	typedef struct
	{
		uint16_t ID;
		uint16_t prop;
		uint16_t len;
		char *data;
	} Instruction;
#pragma pack(pop)

#pragma pack(push,1)
	typedef union
	{
		uint32_t _int;
		float _float;
	} int_float;
#pragma pack(pop)

	template <typename T>
	void Release(T *object)
	{
		if(object) delete object;
		object = NULL;
	}
	template <typename T>
	T ConvertType(char *data)
	{
		return reinterpret_cast<T>(data);
	}
	template <typename T>
	T GetInstructionArg(char **data)
	{
		T temp;
		temp = *reinterpret_cast<T *>(*data);
		*data += sizeof(T);
		return temp;
	}

	float int2float(uint32_t arg);
	uint32_t float2int(float arg);

	class GlobalScript
	{
	private:
		ScriptHeader Header;
		SectionHeader CodeHeader;
		SectionHeader DataHeader;
		SectionHeader EntryHeader;
		vector<EntryData> Entry;

		uint32_t Stack[65536];
		uint32_t SP, BP;
		
		unsigned int MainLoopEntry;
		unsigned int DrawLoopEntry;
		unsigned int InitializeEntry;

		list<Danmaku> DanmakuList;

		uint32_t A, B, X, Y;
		bool Z, C;

		uint16_t PropMask;

		IDirect3DDevice9 **ParentDevice;
		IDirect3DTexture9 *BulletTex[5];
		ID3DXFont *Font;

		bool DanmakuActionLoop();
		bool ExecuteCustomEntry(unsigned int ID);
		bool ExecuteCustomEntry(unsigned int ID, Danmaku &danmaku);

		uint32_t ReadDWORD(char *target);
		void WriteDWORD(char *target, uint32_t value);

		void UpdateRegister(uint16_t flag);
	public:
		GlobalScript()
		{
			A = B = 0;
			Z = C = false;
			PropMask = 0;
			MainLoopEntry = DrawLoopEntry = 0xFFFFFFFF;
			ParentDevice = NULL;
			for(unsigned int i = 0; i < 5; i++) {
				BulletTex[i] = NULL;
			}
			Font = NULL;
			Entry.clear();
			DanmakuList.clear();
			SP = BP = 0;
		}
		GlobalScript(IDirect3DDevice9 **Device)
		{
			A = B = 0;
			Z = C = false;
			PropMask = 0;
			MainLoopEntry = DrawLoopEntry = 0xFFFFFFFF;
			ParentDevice = Device;

			for(unsigned int i = 0; i < 5; i++) {
				BulletTex[i] = NULL;
			}
			Font = NULL;

			D3DXCreateTextureFromFileEx(
				*ParentDevice,
				L"bullet\\bullet1.png",
				D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT,
				0, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED,
				D3DX_DEFAULT, D3DX_DEFAULT, 0x00000000,
				NULL, NULL,
				&BulletTex[0]);
			D3DXCreateTextureFromFileEx(
				*ParentDevice,
				L"bullet\\bullet2.png",
				D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT,
				0, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED,
				D3DX_DEFAULT, D3DX_DEFAULT, 0x00000000,
				NULL, NULL,
				&BulletTex[1]);
			D3DXCreateTextureFromFileEx(
				*ParentDevice,
				L"bullet\\bullet3.png",
				D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT,
				0, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED,
				D3DX_DEFAULT, D3DX_DEFAULT, 0x00000000,
				NULL, NULL,
				&BulletTex[2]);
			D3DXCreateTextureFromFileEx(
				*ParentDevice,
				L"bullet\\bullet4.png",
				D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT,
				0, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED,
				D3DX_DEFAULT, D3DX_DEFAULT, 0x00000000,
				NULL, NULL,
				&BulletTex[3]);
			D3DXCreateFont(
				*ParentDevice,
				15, 0, 400, 0, FALSE,
				949, 255, 4, 0, L"돋움",
				&Font);

			Entry.clear();
			DanmakuList.clear();
			SP = BP = 0;
		}
		~GlobalScript()
		{
			Release<char>(CodeHeader.description);
			Release<char>(CodeHeader.data);
			Release<char>(DataHeader.description);
			Release<char>(DataHeader.data);
			for(unsigned int i = 0; i < 5; i++) Release<IDirect3DTexture9>(BulletTex[i]);
			Font->Release();

			Entry.clear();
			DanmakuList.clear();
		}
		bool OpenScript(string filename);

		bool MainLoop();
		bool DrawLoop();
		DanmakuException ExecuteInstruction(Instruction &ins, char **EP, Danmaku *danmaku);

		bool ResetDevice(D3DPRESENT_PARAMETERS d3dpp);
	};

	class Danmaku
	{
	private:
		float x, y;
		float direction;
		float speed;
		string ActionEntry;
		unsigned int ActionEntryID;

		int DanmakuType;
		_DanmakuGraphic DanmakuGraphic;

		bool isActive;
		bool ignoreDefaultAction;
	public:
		Danmaku() { ignoreDefaultAction = false; isActive = false; }
		~Danmaku() {}

		void SetActionEntry(unsigned int Entry)
		{
			ActionEntryID = Entry;
		}

		void Action();
		unsigned int GetEntryID() const
		{
			return ActionEntryID;
		}
		bool isIgnoreAction() const
		{
			return ignoreDefaultAction;
		}

		// 탄막 컨트롤 함수
		void SetDanmakuPos(float _x, float _y)
		{
			x = _x, y = _y;
		}
		void SetDanmakuDir(float _direction)
		{
			direction = _direction;
		}
		void SetDanmakuSpd(float _speed)
		{
			speed = _speed;
		}
		void ActivateDanmaku(bool active = true)
		{
			isActive = active;
		}

		// 탄막 정보 함수
		bool isActivated() const
		{
			return isActive;
		}
		float GetDanmakuPosX() const
		{
			return x;
		}
		float GetDanmakuPosY() const
		{
			return y;
		}
		float GetDanmakuDir() const
		{
			return direction;
		}
		float GetDanmakuSpd() const
		{
			return speed;
		}
	};

	// 탄막 색
	enum _DanmakuGraphic
	{
		COLOR_GRAY = 0,
		COLOR_DARKRED,
		COLOR_RED,
		COLOR_MAGENTA,
		COLOR_PINK,
		COLOR_DARKBLUE,
		COLOR_BLUE,
		COLOR_SKYBLUE,
		COLOR_CYAN,
		COLOR_GREEN,
		COLOR_BRIGHTGREEN,
		COLOR_YELLOWGREEN,
		COLOR_DARKYELLOW,
		COLOR_YELLOW,
		COLOR_ORANGE,
		COLOR_WHITE,
	};

	class DanmakuException
	{
	private:
		int code;
	public:
		DanmakuException() { code = unknown; }
		DanmakuException(int ErrorCode) { code = ErrorCode; }
		~DanmakuException() {}

		int GetErrorCode() const { return code; }

		static const int ok = 0;
		static const int unknown = -1;
		static const int missing = 1;
		static const int argerror = 2;

		static const int propmask = 0xFE;
		static const int funcreturn = 0xFF;
		static const int reterror = 0x1FF;
		
		static const int genericerr = 0x100;
	};
}
#endif
